<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

require_once APPPATH . 'dao/configurationManager.php';

class MY_Form_validation extends CI_Form_Validation {

    function __construct($rules = array()) {
        parent::__construct($rules);
    }
    
    private $minZoomLevelErrorClass = array(
        'MINZOOM_LESS_THAN_ZERO' => MINZOOM_LESS_THAN_ZERO_ERROR,
        'MAXZOOM_LESS_THAN_MINZOOM' => MAXZOOM_LESS_THAN_MINZOOM_ERROR,
        'MAXZOOM_GREATER_THAN_SRS_RESOLUTIONS' => MAXZOOM_GREATER_THAN_SRS_RESOLUTIONS_ERROR
    );

    //ejecutarla solo en modo new
    public function uniqueLayerName($name,$isUpdate) {

        
        $msjError = sprintf(LAYER_ALREADY_EXISTS,$name);
        $CI = & get_instance();
        $CI->form_validation->set_message('uniqueLayerName', $msjError);
        if(!$isUpdate) { 
            $tileset = ConfigurationManager::getInstance()->getTileSetDataByName($name);
            return $tileset == null ? true : false;    
        }
        return true;
        
    }
     public function clientExpirationValue($val) {

        
        $msjError = WRONG_CLIENT_EXPIRATION_VALUE;
        $expires = $_POST['expires'];
        
        $CI = & get_instance();
        $CI->form_validation->set_message('clientExpirationValue', $msjError);
        
        return (isset($expires) ? $expires > MIN_CLIENT_EXPIRATION_VALUE && $expires <= MAX_CLIENT_EXPIRATION_VALUE : true) ;
        
    }
    
    public function expirationValue($val) {

        
        $msjError = WRONG_EXPIRATION_VALUE;
        
        $autoExpires = $_POST['autoExpires'];
        $CI = & get_instance();
        $CI->form_validation->set_message('expirationValue', $msjError);
        
        return (isset($autoExpires) ? $autoExpires > MIN_EXPIRATION_VALUE && $autoExpires <= MAX_EXPIRATION_VALUE : true) ;
        
    }
    
    /**
     * Debe haber al menos un SRS configurado
     * Esta Validación la agrego en el controlador para poder acceder a las variables del Post
     * @param type $val
     * @return boolean
     */
    
    public function atLeastOneSRS($val) {

        $msjError = AT_LEAST_ONE_SRS;
        $CI = & get_instance();
        $CI->form_validation->set_message('atLeastOneSRS', $msjError);
        
        $srss = $_POST['srss'];
        
        foreach ($srss as $srs) {
            if (array_key_exists('toggleSRS-' . $srs , $_POST) && $_POST['toggleSRS-' . $srs])
                return true;
        }
        return false; 
    }
    
     public function checkBbox($val) {

        $msjError = '';
        $srsWithError = array();
        $srss = $_POST['srss'];
        
        foreach ($srss as $srs) {
            
            $srsConfigured = array_key_exists('toggleSRS-' . $srs , $_POST) ? $_POST['toggleSRS-' . $srs] : false;
            $srsLimitedBBox = array_key_exists('limitBbox-' . $srs , $_POST) ? $_POST['limitBbox-' . $srs] : false;
            
            if ($srsConfigured && $srsLimitedBBox) {
                $bbox = array(
                    'minX' => $_POST['bboxMinX-' . $srs],
                    'minY' => $_POST['bboxMinY-' . $srs],
                    'maxX' => $_POST['bboxMaxX-' . $srs],
                    'maxY' => $_POST['bboxMaxY-' . $srs]
                );
                $srsData = ConfigurationManager::getInstance()->getGridData($srs);
              
                if ($srsData) {
                    if (!$this->checkBoundingBox($bbox, $srsData['extent'])) {
                        $srsWithError[$srs] = true; // marco el srs con error
                    }
                }
            }
        }
        
        if (count($srsWithError) != 0) {
            foreach ($srsWithError as $srs => $error) {
                $msjError = $msjError . sprintf(BBOX_NOT_ALIGNED_TO_SRS, $srs) . '<br>';
                
            }
            $CI = & get_instance();
            $CI->form_validation->set_message('checkBbox', $msjError);
            return false;
        }
        return true;
    }

    private function checkBoundingBox($bbox, $srsBBox) {
        return (
                floatval($bbox['minX']) >= floatval($srsBBox['minX']) &&
                floatval($bbox['minX']) <= floatval($srsBBox['maxX']) &&
                floatval($bbox['minY']) >= floatval($srsBBox['minY']) &&
                floatval($bbox['minY']) <= floatval($srsBBox['maxY']) &&
                floatval($bbox['maxX']) <= floatval($srsBBox['maxX']) &&
                floatval($bbox['maxX']) >= floatval($srsBBox['minX']) &&
                floatval($bbox['maxY']) <= floatval($srsBBox['maxY']) &&
                floatval($bbox['maxY']) >= floatval($srsBBox['minY'])
                );
    }
    
     public function checkZoomLevels($val) {

        $msjError = '';
        $srsWithError = array();
        $srss = $_POST['srss'];
        foreach ($srss as $srs) {
            $srsConfigured = array_key_exists('toggleSRS-' . $srs , $_POST) ? $_POST['toggleSRS-' . $srs] : false;
            $srsLimitedZoomLevels = array_key_exists('limitZoomLevels-' . $srs , $_POST) ? $_POST['limitZoomLevels-' . $srs] : false;
            $srsData = ConfigurationManager::getInstance()->getGridData($srs);
           
            if ($srsConfigured && $srsLimitedZoomLevels) {
                $minZoom = intval($_POST['minZoomLevel-' . $srs]);
                $maxZoom = intVal($_POST['maxZoomLevel-' . $srs]);
               if($minZoom < 0) {
                   $srsWithError[$srs] = $this->minZoomLevelErrorClass['MINZOOM_LESS_THAN_ZERO'];
               }
               else if ($minZoom > $maxZoom) {
                   $srsWithError[$srs] = $this->minZoomLevelErrorClass['MAXZOOM_LESS_THAN_MINZOOM'];
               }
               else if ($maxZoom >  count($srsData['resolutions'])) {
                   $srsWithError[$srs] = $this->minZoomLevelErrorClass['MAXZOOM_GREATER_THAN_SRS_RESOLUTIONS'];
               }
            }
        }
        
        if (count($srsWithError) != 0) {
            foreach ($srsWithError as $srs => $error) {
                $msjError = $msjError . sprintf($error, $srs) . '<br>';
               
            }
            $CI = & get_instance();
            $CI->form_validation->set_message('checkZoomLevels', $msjError);
            return false;
        }
        return true;
    }
   

    /**
     * Función para la validación de campos con codeigniter. Valida que el campo
     * sólo contenga letras, números o espacios.
     *
     * @param <type> $str El texto contenido en el campo.
     * @return <type>  TRUE si es satisfactorio, FALSE caso contrario.
     */
    public function alphanumericSpace($str) {
        //Obtiene la instancia de CI y establece el mensaje en caso de error.
        $CI = & get_instance();
        $CI->form_validation->set_message('alphanumericSpace', 'El campo %s s&oacute;lo debe contener caracteres alfanum&eacute;ricos y espacios.');

        return (!preg_match('/^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚäëïöüÄËÏÖÜ ]*$/', $str)) ? FALSE : TRUE;
    }

    public function alphaApostropheSpace($str) {
        //Obtiene la instancia de CI y establece el mensaje en caso de error.
        $CI = & get_instance();
        $CI->form_validation->set_message('alphaApostropheSpace', 'El campo %s s&oacute;lo debe contener caracteres alfab&eacute;ticos,
                    acentos, ap&oacute;strofes y espacios.');

        return (!preg_match('/^[a-zA-ZñÑáéíóúÁÉÍÓÚäëïöüÄËÏÖÜ\' ]*$/', $str)) ? FALSE : TRUE;
    }

    public function alphaApostropheSpaceNum($str) {
        //Obtiene la instancia de CI y establece el mensaje en caso de error.
        $CI = & get_instance();
        $CI->form_validation->set_message('alphaApostropheSpaceNum', 'El campo %s s&oacute;lo debe contener caracteres alfab&eacute;ticos,
                    acentos, ap&oacute;strofes y espacios.');

        return (!preg_match('/^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚäëïöüÄËÏÖÜ.\' ]*$/', $str)) ? FALSE : TRUE;
    }

    public function requerido($str) {
        //Obtiene la instancia de CI y establece el mensaje en caso de error.
        $CI = & get_instance();
        $CI->form_validation->set_message('requerido', 'El campo %s es obligatorio.');

        return (trim($str) == 0) ? FALSE : TRUE;
    }

}

?>
